<?php

class billing extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('billing_model');
	}

	public function index()
	{	
		$this->data['title'] = 'Billing';
		
		$this->load->view('billing', $this->data);
	}
	
	public function printReceipt() {
		$this->load->view('receipt');
		
	}

	public function save_order()
	{
		$grand_total = 0;
		$query = $this->db->query('SELECT CURTIME() AS time;');
		foreach ($query->result() as $row) {
			$time = $row->time;
		}

		if ($cart = $this->cart->contents()) {
    		foreach ($cart as $item) {
       			$grand_total = $grand_total + $item['subtotal'];
    		}
		}

		$order = array(
			'customer_id' => $this->session->userdata['logged_in']['id'],
			'order_date' => date('Y-m-d'),
			'order_time' => $time,
			'total' => $grand_total,
			'creditcard_number' => $this->input->post('number'),
			'creditcard_month' 	=> $this->input->post('month'),
			'creditcard_year' 	=> $this->input->post('year')
		);

		$ord_id = $this->billing_model->insert_order($order);

		if ($cart = $this->cart->contents()) {
			foreach ($cart as $item) {
				$order_item = array(
					'order_id' 		=> $ord_id,
					'product_id' 	=> $item['id'],
					'quantity' 		=> $item['qty'],
				);		

				$this->billing_model->insert_order_item($order_item);
			}
		}

		$toemail = $this->session->userdata['logged_in']['email'];
		$subject = "Purchase Receipt";
		$message = $this->load->view('receipt','', true);
		
		$config = array ('protocol' => 'stmp',
						'stmp_host' => 'ssl://smtp.gmail.com',
						'stmp_port' => '465',
						'smtp_tiemout' => '7',
						'smtp_user' => 'thecandystore00@gmail.com',
						'smtp_pass' => 'paulslava',
						'charset' => 'utf-8',
						'mailtype' => 'html',
						'newline' => '\r\n');
						
		$this->email->initialize($config);
		$this->email->from('thecandystore00@gmail.com', 'Admin');
		$this->email->to($toemail);
		$this->email->subject($subject);
		$this->email->message($message);
		
		$this->email->send();

		$this->cart->destroy();
		
		echo "Thank You! Your order has been placed!<br />";
		echo br();
		echo "<a href='printReceipt' target='_blank'>View Receipt</a>";
		echo anchor('home', 'Go Back To Products');
	}
}
